package cn.skyclass.utils
{
	/**
	 * size formatter for byte number
	 */
	public class SizeFormatter
	{
		public function SizeFormatter(size:Number) {
			this.size = size;
		}
		
		public static const KB:Number = 1024.0; // ==2e10	
		public static const MB:Number = 1048576.0; // ==2e20	
		public static const GB:Number = 1073741824.0; // ==2e30	
		public static const TB:Number = 1099511627776.0; // ==2e40		
				
		private var size:Number;
	
		public function getOriginalSize():Number {
			return this.size;
		}
		
		public static function format(size:Number, precision:int=2):String {
			var sf:SizeFormatter = new SizeFormatter(size);
			return sf.toString(precision);
		}		
		
		private function format(value:Number, precision:int, suffix:String):String {
			var point:int = value.toString().indexOf(".");
			if(point < 0){
				return value.toString() + " " + suffix;
			}else{
				return value.toPrecision(point + precision) + " " + suffix;
			}
		}
	
		public function toString(precision:int=2):String {
			if (size < 0) {
				return "--";
			} else if (size < KB) {
				return size + " B";
			} else if (size < MB) {
				return this.format(size / KB, precision, "KB");
			} else if (size < GB) {
				return this.format(size / MB, precision, "MB");
			} else if (size < TB) {
				return this.format(size / GB, precision, "GB");
			} else {
				return this.format(size / TB, precision, "TB");
			}
		}
	
	}
}